/*******************************************************************************
 * Copyright 2011 Mauro Luigi Drago (drago.luigi@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.bytenose.extrautils.patterns.builder;

import com.bytenose.extrautils.annotations.NonNullable;

/**
 * A builder of objects which performs sanity checks before actually creating
 * objects. Sanity checks may be performed before building by using the 
 * {@link CheckedBuilder#check()} or {@link CheckedBuilder#isCorrect()} methods.
 * Sanity checks must be also performed before building the object through
 * the {@link CheckedBuilder#build()} method. 
 * @author Mauro Luigi Drago
 *
 * @param <O>  the type of objects this builder creates.
 * @param <ET> the type of errors generated by sanity checks.
 */
public interface CheckedBuilder<O,ET extends Exception> {
	/**
	 * Creates a new object of type O.
	 * The contract of this method imposes to perform sanity checks
	 * before creating the new object and returning it.
	 * It is not necessary to perform these checks by invoking
	 * the {@link #check()} or the {@link #isCorrect()} method.
	 * Checks may be performed by custom code, but should be consistent
	 * with the checks performed by those two methods.
	 * @return the new object.
	 * @throws ET if sanity checks or the build failed. 
	 */
	@NonNullable O build() throws ET;
	
	/**
	 * Creates a new object of type O swallowing potential exceptions.
	 * When sanity checks fail, this method should return null instead
	 * of an exception. 
	 * The contract of this method imposes to perform sanity checks
	 * before creating the new object and returning it.
	 * It is not necessary to perform these checks by invoking
	 * the {@link #check()} or the {@link #isCorrect()} method.
	 * Checks may be performed by custom code, but should be consistent
	 * with the checks performed by those two methods.
	 * @return the new object, or null if sanity checks or the build failed.
	 */
	O buildSwallow();
	
	/**
	 * Performs sanity checks on the builder, checking if objects can be built.
	 * @return an immutable iterable of found problems.
	 */
	@NonNullable Iterable<ET> check();
	
	/**
	 * Performs sanity checks on the builder, checking if objects can be built.
	 * @return false if sanity checks failed, true otherwise. 
	 */
	boolean isValid();
}
